package licode.unisop.authcenter.application.executor;

import licode.unisop.authcenter.application.info.*;
import licode.unisop.platform.client.api.SiPlatformQueryService;
import licode.unisop.provider.info.*;
import licode.unisop.provider.utils.StrUtil;
import licode.unisop.provider.vo.*;
import licode.unisop.realm.client.api.SiUserQueryService;
import licode.unisop.types.AuthConst;
import licode.unisop.types.dp.UserAuthIn;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定义统一认证平台中心平台查询相关接口
 *
 * @author licode
 */
@Service
public class CenterPlatformQueryExecutor {
    @Resource
    private SiUserQueryService siUserQueryService;

    @Resource
    private SiPlatformQueryService siPlatformQueryService;

    public SiPageResult<SiUser> queryUserPage(PlatUserQueryPageIn req) {
        SiPlatform platform = siPlatformQueryService.lookupPlatform(SiPlatIdFind.builder()
                .platformId(req.getPlatformId())
                .build());
        if (null == platform || StrUtil.isBlank(platform.getRealmId())) {
            return null;
        } else {
            List<SiUserGroup> groups = siUserQueryService.findRealmGroupsOfPlatform(UserGroupQueryIn.builder()
                    .realmId(platform.getRealmId())
                    .platformId(platform.getId())
                    .build());

            if (null == groups || groups.isEmpty()) {
                return null;
            } else {
                return siUserQueryService.findPage(UserPageInfo.builder()
                        .current(req.getCurrent())
                        .pageSize(req.getPageSize())
                        .realmId(platform.getRealmId())
                        .userName(req.getName())
                        .state(req.getState())
                        .neState(req.getNeState())
                        .groups(groups.stream().map(SiUserGroup::getId).collect(Collectors.toList()))
                        .build());
            }
        }
    }

    private SiAssetHold getCurrentUserAssets(UserAuthIn authIn) {
        SiHoldInfo holdInfo = SiHoldInfo.builder()
                .holdId(authIn.getUserId())
                .clientId(authIn.getClientId())
                .tenantId(authIn.getTenantId())
                .platformId(authIn.getPlatformId())
                .build();

        SiAssetHold assetHold = siPlatformQueryService.getUserAssets(holdInfo);

        if (null != assetHold && null != assetHold.getCodes()) {
            Map<String, String> roleCodes = assetHold.getCodes().get("ROLE");
            // 超级管理员，重新获取所有资源
            if (null != roleCodes && roleCodes.containsKey(AuthConst.SYSTEM_ADMIN)) {
                holdInfo.setHoldId("");
                assetHold = siPlatformQueryService.getUserAssets(holdInfo);
            }
        }

        return assetHold;
    }

    private boolean containUserRole(UserAuthIn authIn, String roleCode) {
        SiAssetHold assetHold = getCurrentUserAssets(authIn);
        if (null == assetHold || null == assetHold.getCodes()) {
            return false;
        }
        Map<String, String> roleCodes = assetHold.getCodes().get("ROLE");
        if (roleCodes == null) {
            return false;
        }
        return roleCodes.containsKey(roleCode);
    }

    public SiPageResult<SiPlatform> queryPage(UserAuthIn authIn, PlatformQueryPageIn req) {
        int needAuthPlat = containUserRole(authIn, AuthConst.SYSTEM_ADMIN) ? 0 : 1;
        return siPlatformQueryService.findPlatformPage(PlatPageInfo.builder()
                .current(null != req.getCurrent() ? req.getCurrent() : 1)
                .pageSize(null != req.getPageSize() ? req.getPageSize() : 20)
                .name(req.getName())
                .state(req.getState())
                .userId(needAuthPlat == 1 ? authIn.getUserId() : "")
                .startTime(req.getStartTime())
                .endTime(req.getEndTime())
                .build());
    }

    public SiPageResult<SiPlatform> queryAuthPage(UserAuthIn authIn, AuthPlatformQueryPageIn req) {
        SiPageResult<SiPlatform> plats = queryPage(authIn, PlatformQueryPageIn
                .builder()
                .current(req.getCurrent())
                .pageSize(req.getPageSize())
                .name(req.getName()).build());
        if (null != plats && null != plats.getData() && !plats.getData().isEmpty()) {
            List<String> platIds = plats.getData().stream().map(SiPlatform::getId)
                    .collect(Collectors.toList());
            SiPageResult<String> authIds = siPlatformQueryService.findAuthPlatformPage(AuthPlatPageInfo.builder()
                    .userId(req.getUserId())
                    .current(1)
                    .pageSize(platIds.size())
                    .build());
            if (null != authIds && null != authIds.getData()) {
                boolean isSystemUser = !StrUtil.isBlank(req.getUserId()) && containUserRole(UserAuthIn.builder()
                        .platformId(AuthConst.SSO_MANAGER_PLATFORM_ID)
                        .userId(req.getUserId()).build(), AuthConst.SYSTEM_ADMIN);

                plats.getData().forEach(item -> {
                    if (isSystemUser || authIds.getData().contains(item.getId())) {
                        if (null == item.getProps()) {
                            item.setProps(new SiProps());
                        }
                        item.getProps().addProp("$auth", 1);
                        if (isSystemUser) {
                            item.getProps().addProp("$disable", 1);
                        }
                    }
                });
            }

        }
        return plats;
    }

    /**
     * 查询平台信息
     */
    public SiPlatform lookup(PlatformLookupIn req) {
        return siPlatformQueryService.lookupPlatform(SiPlatIdFind.builder()
                .platformId(req.getPlatformId()).build());
    }

    /**
     * 查询平台租户信息
     */
    public SiPageResult<SiPlatform> queryTenantPage(PlatTenantQueryPageIn req) {
        return null;
    }

    /**
     * 查询平台产品信息
     */
    public SiPageResult<SiPlatform> queryProductPage(PlatProductQueryPageIn req) {
        return null;
    }

    /**
     * 查询平台应用信息
     */
    public SiPageResult<SiPlatform> queryApplicationPage(PlatApplicationQueryPageIn req) {
        return null;
    }
}
